﻿using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace IceDog.EFCore.Cmd.DBFirst.Models
{
    public partial class DioBlogContext : DbContext
    {
        public DioBlogContext()
        {
        }

        public DioBlogContext(DbContextOptions<DioBlogContext> options)
            : base(options)
        {
        }

        public virtual DbSet<BlogArticles> BlogArticles { get; set; }
        public virtual DbSet<BlogComments> BlogComments { get; set; }
        public virtual DbSet<BlogUsers> BlogUsers { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlite("Data Source=DioBlog.db;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<BlogArticles>(entity =>
            {
                entity.HasKey(e => e.ArticleId);

                entity.HasIndex(e => e.AuthorId);

                entity.Property(e => e.ArticleId).ValueGeneratedNever();

                entity.Property(e => e.CreateTime).IsRequired();

                entity.HasOne(d => d.Author)
                    .WithMany(p => p.BlogArticles)
                    .HasForeignKey(d => d.AuthorId);
            });

            modelBuilder.Entity<BlogComments>(entity =>
            {
                entity.HasKey(e => e.CommentId);

                entity.HasIndex(e => e.ArticleId);

                entity.HasIndex(e => e.CommenterId);

                entity.Property(e => e.CommentId).ValueGeneratedNever();

                entity.Property(e => e.CommentTime).IsRequired();

                entity.HasOne(d => d.Article)
                    .WithMany(p => p.BlogComments)
                    .HasForeignKey(d => d.ArticleId);

                entity.HasOne(d => d.Commenter)
                    .WithMany(p => p.BlogComments)
                    .HasForeignKey(d => d.CommenterId);
            });

            modelBuilder.Entity<BlogUsers>(entity =>
            {
                entity.HasKey(e => e.UserId);

                entity.Property(e => e.UserId).ValueGeneratedNever();
            });
        }
    }
}
